/**
 * axios 实例
 */
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import router from '@/router'

const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 30000
})

/**
 * 添加请求拦截器
 */
/* eslint-disable */
service.interceptors.request.use(
  (config) => {
    // 是否需要设置 token
    const token = localStorage.getItem('Authorization')
    // 添加 token 到 header
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?'
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName]
        const part = encodeURIComponent(propName) + '='
        if (value !== null && typeof (value) !== 'undefined') {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              const params = propName + '[' + key + ']'
              const subPart = encodeURIComponent(params) + '='
              url += subPart + encodeURIComponent(value[key]) + '&'
            }
          } else {
            url += part + encodeURIComponent(value) + '&'
          }
        }
      }
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

/**
 * 添加响应拦截器
 */
service.interceptors.response.use(res => {
  console.log('HTTP响应拦截数据', res)
  // 未设置状态码则默认成功状态
  const code = res.data.code || 200
  // 登录过期处理
  if (code === 200) {
    return res.data
  } else if (code === 401) {
    const currentPath = router.currentRoute.path
    console.log(401, currentPath)
    if (currentPath !== '/login') { 
      MessageBox.alert('登录状态已过期, 请退出重新登录!', '系统提示', {
        confirmButtonText: '重新登录',
        callback: (action) => {
          if (action === 'confirm') {
            router.push({
              path: '/login',
              query: { 
                from: currentPath
              }
            })
          }
        },
        beforeClose: () => {
          MessageBox.close()
        }
      })
    }
  } else {
    Message({
      message: res.data.msg,
      type: 'error'
    })
    return res.data
  }
}, error => {
  let { message } = error
  if (message === 'Network Error') {
    message = '后端接口连接异常'
  } else if (message.includes('timeout')) {
    message = '系统接口请求超时'
  } else if (message.includes('Request failed with status code')) {
    message = '系统接口' + message.substr(message.length - 3) + '异常'
  }
  Message({
    message: message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
}
)

export default service
